package com.txhy.certificatechain.ui.fragment.bottomnavigation;

import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.txhy.certificatechain.R;
import com.txhy.certificatechain.api.UrlAddress;
import com.txhy.certificatechain.model.bean.ArticleBean;
import com.txhy.certificatechain.model.bean.BannerBean;
import com.txhy.certificatechain.model.bean.FrgHomeBean;
import com.txhy.certificatechain.model.bean.NewsBean;
import com.txhy.certificatechain.presenter.home.HomePresenter;
import com.txhy.certificatechain.ui.activity.base.BaseFragment;
import com.txhy.certificatechain.ui.adapter.FragHomeGdAdapter;
import com.txhy.certificatechain.ui.adapter.FragHomeGdXianAdapter;
import com.txhy.certificatechain.ui.adapter.HomeRecyListAdapter;
import com.txhy.certificatechain.ui.manager.ImageLoaderManager;
import com.txhy.certificatechain.ui.view.index.IndexView;
import com.txhy.certificatechain.utils.CommUtils;
import com.txhy.certificatechain.utils.GsonUtil;
import com.txhy.certificatechain.utils.PrefUtil;
import com.txhy.certificatechain.utils.ToastUtil;
import com.txhy.certificatechain.utils.UIUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.bgabanner.BGABanner;

/*
 * -----------------------------------------------------------------
 * Copyright (C) 2018-2030, by your company, All rights reserved.
 * -----------------------------------------------------------------
 * 文    件: ShopFragment.java
 * 作    者: 侯建军
 * 版    权: 1.0.0
 * 描    述: 商城--底部导航
 * 创建时间: 2018/9/20 9:04
 * 更新时间：2018/9/20 9:04
 * -----------------------------------------------------------------
 * 2018/9/20 9:04: 创建 ShopFragment.java (侯建军);
 * -----------------------------------------------------------------
 */
public class ShopFragment extends BaseFragment<IndexView, HomePresenter>
        implements IndexView {


    @BindView(R.id.gd_home)
    GridView gd_home;

    @BindView(R.id.gd_horizon)
    GridView gd_horizon;

    @BindView(R.id.ll_top)
    LinearLayout ll_top;
    @BindView(R.id.flipper)
    ViewFlipper flipper;


    @BindView(R.id.tv_time)
    TextView tv_time;

    @BindView(R.id.tv_shi)
    TextView tv_shi;
    @BindView(R.id.tv_minter)
    TextView tv_minter;
    @BindView(R.id.tv_second)
    TextView tv_second;

    @BindView(R.id.banner)
    BGABanner mBannerView;
    @BindView(R.id.banner_middle)
    BGABanner banner_middle;

    @BindView(R.id.rv_content)
    RecyclerView rv_content;


    private HomeRecyListAdapter mAdapter;


    //使用handler用于更新UI
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            countDown();
            sendEmptyMessageDelayed(0, 1000);
        }
    };

    public static ShopFragment newInstance() {
        return new ShopFragment();
    }

    @Override
    protected HomePresenter createPresenter() {
        return new HomePresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.frag_index_center;
    }


    @Override
    public void initView(View rootView) {
        //让ScrollView和RecycleView滑动流畅
        rv_content.setHasFixedSize(true);
        rv_content.setNestedScrollingEnabled(false);
        //让ScrollView和RecycleView滑动流畅
        //使ScrollView在顶部
        ll_top.setFocusable(true);
        ll_top.setFocusableInTouchMode(true);
        ll_top.requestFocus();//使ScrollView在顶部
        mPresenter.getBannerData("webLb");
        mPresenter.getNewsData("2");

        mPresenter.getBannerData("appMallLb");

        ArrayList<FrgHomeBean> list = new ArrayList<>();
        list.add(new FrgHomeBean(R.mipmap.hshoujishu, UIUtils.getString(R.string.hshouji)));
        list.add(new FrgHomeBean(R.mipmap.hjiayong, UIUtils.getString(R.string.hjiazhuang)));
        list.add(new FrgHomeBean(R.mipmap.hshipingbao, UIUtils.getString(R.string.hshiping)));
        list.add(new FrgHomeBean(R.mipmap.hhuwai, UIUtils.getString(R.string.hhuwai)));
        list.add(new FrgHomeBean(R.mipmap.hfushi, UIUtils.getString(R.string.hfushi)));
        list.add(new FrgHomeBean(R.mipmap.htushu, UIUtils.getString(R.string.htushu)));
        list.add(new FrgHomeBean(R.mipmap.hjiazhuang, UIUtils.getString(R.string.hjiazhuang)));
        list.add(new FrgHomeBean(R.mipmap.hshenghuo, UIUtils.getString(R.string.hshenghuo)));
        list.add(new FrgHomeBean(R.mipmap.hjiaoyu, UIUtils.getString(R.string.hjiaoyu)));
        list.add(new FrgHomeBean(R.mipmap.hquanbu, UIUtils.getString(R.string.hquanbu)));
        gd_home.setAdapter(new FragHomeGdAdapter(list, getActivity(), 5));
        gd_home.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                startActivity(new Intent(getActivity(), ShoppingListActivity.class));
            }
        });
        gd_horizon.setAdapter(new FragHomeGdXianAdapter(null, getActivity()));
        gd_horizon.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//
//                Intent intent = new Intent(getActivity(), GoodDetailsActivity.class);
//                intent.putExtra("id", "898321161032704");
//                intent.putExtra("type", "1");
//                startActivity(intent);
            }
        });

//        mPresenter.getBannerData();


//        倒计时秒杀
        handler.sendEmptyMessage(0);


//今日必买
        rv_content.setLayoutManager(new LinearLayoutManager(getContext()));
        ArrayList<ArticleBean> list1 = new ArrayList<>();
        list1.add(new ArticleBean());
        list1.add(new ArticleBean());
        list1.add(new ArticleBean());
        mAdapter = new HomeRecyListAdapter(getContext(), list1);
        rv_content.setAdapter(mAdapter);
    }

    @Override
    public void getBannerSuccess(String data) {

        BannerBean bean = GsonUtil.GsonToBean(data,BannerBean.class);
        //设置轮播图
        mBannerView.setData(R.layout.item_banner, bean.getData(), null);
        mBannerView.setAdapter(new BGABanner.Adapter<View, BannerBean.DataEntity>() {
            @Override
            public void fillBannerItem(BGABanner banner, View itemView,BannerBean.DataEntity model, int position) {
                ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
                imageView.setImageResource(R.mipmap.ic_launcher);
                ImageLoaderManager.LoadImage(getContext(), UrlAddress.IMGBASE_URL + model.getImgUrl(), imageView);
            }
        });
        mBannerView.setDelegate(new BGABanner.Delegate<View, BannerBean.DataEntity>() {
            @Override
            public void onBannerItemClick(BGABanner banner, View itemView, BannerBean.DataEntity model, int position) {
//                WebViewActivity.runActivity(getContext(), model.getUrl());

            }
        });
    }

    @Override
    public void getBannerFail(String message) {
        ToastUtil.showLong(getActivity(), message);
    }

    @Override
    public void getShopBannerSuccess(String data) {

      BannerBean bean = GsonUtil.GsonToBean(data, BannerBean.class);
        //设置轮播图
        banner_middle.setData(R.layout.item_banner, bean.getData(), null);
        banner_middle.setAdapter(new BGABanner.Adapter<View, BannerBean.DataEntity>() {
            @Override
            public void fillBannerItem(BGABanner banner, View itemView, BannerBean.DataEntity model, int position) {
                ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
                imageView.setImageResource(R.mipmap.ic_launcher);
                ImageLoaderManager.LoadImage(getContext(), UrlAddress.IMGBASE_URL + model.getImgUrl(), imageView);
            }
        });
        banner_middle.setDelegate(new BGABanner.Delegate<View, BannerBean.DataEntity>() {
            @Override
            public void onBannerItemClick(BGABanner banner, View itemView,BannerBean.DataEntity model, int position) {
//                WebViewActivity.runActivity(getContext(), model.getUrl());

            }
        });

    }

    @Override
    public void getNewsSuccess(String user) {
        NewsBean bean = GsonUtil.GsonToBean(user, NewsBean.class);
        for (int i = 0; i < bean.getData().size(); i++) {
            final View ll_content = View.inflate(getActivity(), R.layout.item_flipper, null);
            TextView tv_content = (TextView) ll_content.findViewById(R.id.tv_content);
            TextView tv_content_two = (TextView) ll_content.findViewById(R.id.tv_content_two);
            ImageView img_img = (ImageView) ll_content.findViewById(R.id.img_img);
            tv_content.setText(bean.getData().get(i).getTitle());
            tv_content_two.setText(bean.getData().get(i).getDetail());
            ImageLoaderManager.LoadImage(getActivity(), UrlAddress.IMGBASE_URL + bean.getData().get(i).getLogoUrl(), img_img);
            flipper.addView(ll_content);
        }
    }

    @Override
    public void getNewsFail(String msg) {
        ToastUtil.showLong(getActivity(), msg);
    }

    /**
     * 秒杀
     */
    private void countDown() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        String format = df.format(curDate);
        StringBuffer buffer = new StringBuffer();
        String substring = format.substring(0, 11);
        buffer.append(substring);
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour % 2 == 0) {
            tv_time.setText(hour + 1 + "点场");
            buffer.append((hour + 2));
            buffer.append(":00:00");
        } else {
            tv_time.setText((hour + 1) + "点场");
            buffer.append((hour + 1));
            buffer.append(":00:00");
        }
        String totime = buffer.toString();
        try {
            java.util.Date date = df.parse(totime);
            java.util.Date date1 = df.parse(format);
            long defferenttime = date.getTime() - date1.getTime();
            long days = defferenttime / (1000 * 60 * 60 * 24);
            long hours = (defferenttime - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
            long minute = (defferenttime - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
            long seconds = defferenttime % 60000;
            long second = Math.round((float) seconds / 1000);
            tv_shi.setText("0" + hours + "");
            if (minute >= 10) {
                tv_minter.setText(minute + "");
            } else {
                tv_minter.setText("0" + minute + "");
            }
            if (second >= 10) {
                tv_second.setText(second + "");
            } else {
                tv_second.setText("0" + second + "");
            }


        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.img_peop, R.id.img_buyCard, R.id.img_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_peop:
                if (!PrefUtil.getLoginBoolean(getActivity())) {
                    CommUtils.doToLoad(getActivity());
                    return;
                }
//                startActivity(new Intent(getActivity(), ShopPersonCenterActivity.class));
                break;
            case R.id.img_buyCard:
                if (!PrefUtil.getLoginBoolean(getActivity())) {
                    CommUtils.doToLoad(getActivity());
                    return;
                }
//                startActivity(new Intent(getActivity(), BuyCardActivity.class));
                break;
            case R.id.img_share:
//                startActivity(new Intent(getActivity(), ShareActivity.class));
                break;
        }
    }
}
